package br.com.condominio.dao;

// default package
// Generated 19/04/2012 00:23:01 by Hibernate Tools 3.4.0.CR1

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.condominio.entity.Bloco;

@Repository("blocoDao")
public class BlocoDAO {

	private static final Log log = LogFactory.getLog(BlocoDAO.class);

	@PersistenceContext
	private EntityManager entityManager;

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Bloco> findAll() {
		log.debug("findAll Bloco instance");
		try {
			String jpql = "SELECT c from Bloco c order by c.residencial.resNome, c.bloDescricao";
			Query query = entityManager.createQuery(jpql);
			List<Bloco> blocos = (List<Bloco>) query
					.getResultList();
			return blocos;
		} catch (RuntimeException re) {
			log.error("findAll failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Bloco> findByName(String string) {
		log.debug("findByName Bloco instance");
		try {
			String jpql = " SELECT c from Bloco c where bloDescricao like :bloDescricao order by c.bloDescricao";
			Query query = entityManager.createQuery(jpql);
			query.setParameter("bloDescricao", string + "%");
			List<Bloco> blocos = (List<Bloco>) query
					.getResultList();
			return blocos;
		} catch (RuntimeException re) {
			log.error("findByName failed", re);
			throw re;
		}
	}

	@Transactional
	public Bloco persist(Bloco transientInstance) {
		log.debug("persisting Bloco instance");
		try {
			entityManager.persist(transientInstance);
			log.debug("persist successful");
			return transientInstance;
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	
	@Transactional
	public void delete(Bloco bloco) {
		bloco = entityManager.find(Bloco.class,
				bloco.getBloCodigo());
		entityManager.remove(bloco);
	}

	@Transactional
	public Bloco merge(Bloco detachedInstance) {
		log.debug("merging Bloco instance");
		try {
			Bloco result = entityManager.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	@Transactional
	public Bloco findById(Integer id) {
		log.debug("getting Bloco instance with id: " + id);
		try {
			Bloco instance = entityManager.find(Bloco.class, id);
			log.debug("get successful");
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
}
